package com.xiaofeinode.servlet;

import cn.hutool.json.JSONUtil;
import com.xiaofeinode.service.UserService;
import com.xiaofeinode.service.impl.UserServiceImpl;
import com.xiaofeinode.utils.RespResultUtil;
import com.xiaofeinode.utils.ResultUtils;
import javafx.embed.swt.SWTFXUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet("/user")
public class UserServlet extends HttpServlet {
    private UserService userService = new UserServiceImpl();

    @Override
    public void service(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {

        res.setCharacterEncoding("utf-8");
        res.setContentType("application/json");

        String value =  req.getParameter("value");
        switch (value){
            case "add":{
                add(req,res);
            }
            case "delete":{
                delete(req,res);
            }
            case "select":{
                select(req,res);
            }
            case "update":{
                update(req,res);
            }
        }
    }

    private void update(HttpServletRequest req, HttpServletResponse res) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        String username = req.getParameter("username");
        String password = req.getParameter("password");

        ResultUtils update = userService.update(id, username, password);
        RespResultUtil.write(update,res);
    }

    private void select(HttpServletRequest req, HttpServletResponse res) throws IOException {
        ResultUtils result = userService.select();
        RespResultUtil.write(result,res);
    }

    private void delete(HttpServletRequest req, HttpServletResponse res) throws IOException {
        Integer id = Integer.valueOf(req.getParameter("id"));
        ResultUtils result = userService.delete(id);
        RespResultUtil.write(result,res);
    }

    private void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println(username + password);
        ResultUtils result = userService.add(username,password);

        RespResultUtil.write(result,response);
    }
}
